﻿using System;
using Plugins.Core.Interfaces;

namespace Plugins.Core
{
    [Serializable]
    public class PluginConnector<T> : IPluginConnector<T>
    {
        private T _obj;
        private PluginConnectionState _state;
        protected virtual bool CanAttach(T obj) { return object.Equals(_obj, default(T)); }
        protected virtual bool AttachConnector(T obj)
        {
            if (!CanAttach(obj))
            {
                return false;
            }
            else
            {
                _state = PluginConnectionState.Default;
                return true;
            }
        }
        public bool Attach(T key)
        {
            lock (this)
            {
                if (AttachConnector(key))
                {
                    _obj = key;
                    return true;
                }
                return false;
            }
        }
        protected virtual bool CanDetach(T obj) { return object.Equals(_obj, obj); }
        protected virtual bool DetachConnector(T key)
        {
            if (!CanDetach(key))
            {
                return false;
            }
            else
            {
                _state = PluginConnectionState.None;
                return true;
            }
        }
        public bool Detach(T key)
        {
            lock (this)
            {
                if (DetachConnector(key))
                {
                    _obj = default(T);
                    return true;
                }
                return false;
            }
        }
        protected T Object { get { return _obj; } }
        protected PluginConnectionState State { get { return _state; } }
    }
}
